//
//  UIImage+EL.m
//  jobClient
//
//  Created by 一览iOS on 2017/6/26.
//  Copyright © 2017年 YL1001. All rights reserved.
//

#import "UIImage+EL.h"

@implementation UIImage (EL)

#pragma mark - 生成二维码<##>
+ (UIImage *)qrImageForString:(NSString *)string imageSize:(CGFloat)Imagesize{
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKey:@"inputMessage"];//通过kvo方式给一个字符串，生成二维码
    //@"L", @"M", @"Q", @"H" 容错率由低到高 纠错水平，越高纠错水平越高，可以污损的范围越大
    [filter setValue:@"M" forKey:@"inputCorrectionLevel"];//设置二维码的
    CIImage *outPutImage = [filter outputImage];//拿到二维码图片
    return [[[UIImage alloc] init] createNonInterpolatedUIImageFormCIImage:outPutImage withSize:Imagesize];
}

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    CGColorSpaceRelease(cs);
    
    UIImage *img = [UIImage imageWithCGImage:scaledImage];
    CGImageRelease(scaledImage);
    return img;
}

@end
